#include"xtcp_buffer.h"

void tcp_buffer_init(xtcp_buffer_t * buffer){
    buffer->data_count=buffer->unack_count=0;
    buffer->front=buffer->tail=buffer->next=0;
};

//信息函数
uint16_t tcp_buffer_free_size(xtcp_buffer_t * buffer){
    //获取tcp缓冲区的空闲区域大小
    return XTCP_CFG_RTX_BUF_SIZE- buffer->data_count;
} 

uint16_t tcp_buffer_wait_send_size(xtcp_buffer_t * buffer){
    //获取tcp缓冲区的等待发送数据的大小
    return buffer->data_count-buffer->unack_count;
} 

//数据
void tcp_buffer_add_acked_count(xtcp_buffer_t *buffer,uint16_t size){
    //增加已确认的数据，收到对方发来的ack的时候调用
    buffer->tail+=size;
    if(buffer->tail>=XTCP_CFG_RTX_BUF_SIZE){
        buffer->tail-=XTCP_CFG_RTX_BUF_SIZE;
    }
    buffer->unack_count-=size;
    buffer->data_count-=size;
}


//数据 --> tcp缓冲区 从front往后写
uint16_t tcp_buffer_write(xtcp_buffer_t * tcp_buffer,uint8_t * from,uint16_t size){
    size=min(tcp_buffer_free_size(tcp_buffer),size);

    for(int i=0;i<size;i++){
        tcp_buffer->data[tcp_buffer->front++]=from[i];
        if(tcp_buffer->front >= XTCP_CFG_RTX_BUF_SIZE){
            tcp_buffer->front -= XTCP_CFG_RTX_BUF_SIZE;
        }
    }    
    tcp_buffer->data_count+=size;
    return size;
}


//tcp缓冲区 --> to 从next开始读取的
uint16_t tcp_buffer_read(xtcp_buffer_t * tcp_buffer,uint8_t * to,uint16_t size){
    size=min(tcp_buffer_wait_send_size(tcp_buffer),size);

    for(int i=0;i<size;i++){
        to[i]=tcp_buffer->data[tcp_buffer->next++];
        if(tcp_buffer->next >= XTCP_CFG_RTX_BUF_SIZE){
            tcp_buffer->next -= XTCP_CFG_RTX_BUF_SIZE;
        }
    }    
    tcp_buffer->unack_count+=size;
    return size;
}